from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.utils.feedgenerator import Atom1Feed
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.contrib.syndication.feeds import Feed
from django.db.models import Sum, Count

from tagging.models import TaggedItem

from models import Language, Snippet


current_site = Site.objects.get_current().name

data = {"tags" : ("tagged with %s", "Snippets relating to %s"),
        "languages": ("written in %s", "Snippets written in %s"),
        "users": ("by %s", "%s's Snippets"),
        "rating": ("ordered by rating score", "Highest rated snippets"),
        "bookmarks": ("ordered by number of bookmarks","Most bookmarked snippets")}

class SnippetsRSS(Feed):
    """
    Feed of the most recently published Snippets.
    
    """
    title_template = 'cab/feeds/title.html'
    description_template = 'cab/feeds/description.html'
    item_copyright = 'Freely redistributable'
    
    link = "/snippets/"
    

    def get_object(self, args):
        if not args:
            return
        if args[0] in ("rating", "bookmarks"):
            args.append("")
        if len(args) != 2 or args[0] not in data:
            raise ObjectDoesNotExist
        return args
    
    
    def items(self, obj):
        snippets = Snippet.objects.all()
        if obj:
            if obj[0] == "tags":
                snippets = TaggedItem.objects.get_by_model(snippets, obj[1])
            elif obj[0] == "language":
                snippets = snippets.get_by_language(obj[1])
            elif obj[0] == "users":
                snippets = snippets.filter(author__username__exact=obj[1])
            elif obj[0] == "rating":
                snippets = snippets.annotate(score=Sum('rating__score')).filter(score__gt=0).order_by("-score")
            elif obj[0] == "bookmarks":
                snippets = snippets.annotate(bookmarks=Count('bookmark')).filter(bookmarks__gt=0).order_by("-bookmarks")

        return (snippets.count() > settings.RECENT_SNIPPETS_FEED_OBJECTS and
                snippets[:settings.RECENT_SNIPPETS_FEED_OBJECTS] or snippets)    
    
    def item_author_name(self, item):
        return item.author.get_profile().display_name
    
    def item_author_link(self, item):
        return "/profiles/%s/" % item.author.username
    
    def item_link(self, item):
        return item.get_absolute_url()
    
    def item_pubdate(self, item):
        return item.pub_date
    
    def title(self, obj):
        title = "%s: Latest snippets " % current_site
        if obj:            
            if not obj[1]:
                return "%s: Snippets %s" % (current_site, data[obj[0]][0])
            title += data[obj[0]][0] % obj[1] 
        return title
    
    def description(self, obj):
        if not obj:
            return "Latest snippets"
        if obj[1]:
            return data[obj[0]][1] % obj[1]
        return data[obj[0]][1]

class SnippetsAtom(SnippetsRSS):
    feed_type = Atom1Feed
